package com.dhcc.util;


import java.io.*;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.*;

public class StringUtil {

	// 替换换行
	public static String replaceMsg(String msg) {
		return msg.trim().replaceAll(System.getProperty("line.separator"), "");
	}

	// 生成UUID
	public static String getUUID() {
		String str = String.valueOf(System.currentTimeMillis());
		UUID uuid = UUID.nameUUIDFromBytes(str.getBytes());
		return uuid.toString().replace("-", "");
	}

	/**
	 * @函数功能: 判断字符串是否为空
	 * @输入参数: String s 源字符串
	 * @输出结果: true or false
	 */
	public static boolean isEmpty(String s) {
		if (s == null) {
			return true;
		} else if (s.trim().equals("")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @函数功能: 判断字符串是否全是数字
	 * @输入参数: String str 源字符串
	 * @输出结果: true or false
	 */
	public static boolean isAllNumber(String str) {
		if (str == null)
			return false;
		for (int i = 0; i < str.length(); i++)
			if ('0' > str.charAt(i) || str.charAt(i) > '9')
				return false;
		return true;
	}

	/**
	 * @函数功能: 判断字符串是否全是字母
	 * @输入参数: String str 源字符串
	 * @输出结果: true or false
	 */
	public static boolean isAllLetter(String str) {
		if (str == null)
			return false;
		for (int i = 0; i < str.length(); i++)
			if (('A' > str.charAt(i) || str.charAt(i) > 'Z') && ('a' > str.charAt(i) || str.charAt(i) > 'z'))
				return false;
		return true;
	}

	/**
	 * 去除字符串两边空格
	 *
	 * @param str
	 * @return
	 */
	public static String trim(String str) {
		if (str == null || str.equals("")) {
			return str;
		} else {
			return str.replaceAll("^[　 ]+|[　 ]+$", "");
		}
	}

	/**
	 * 去除字符串左边空格
	 *
	 * @param str
	 * @return
	 */
	public static String leftTrim(String str) {
		if (str == null || str.equals("")) {
			return str;
		} else {
			return str.replaceAll("^[　 ]+", "");
		}
	}

	/**
	 * 去除字符串右边空格
	 *
	 * @param str
	 * @return
	 */
	public static String rightTrim(String str) {
		if (str == null || str.equals("")) {
			return str;
		} else {
			return str.replaceAll("[　 ]+$", "");
		}
	}

	/**
	 * @函数功能: 将字符串转换为小写
	 * @输入参数: 待转换的字符串
	 * @输出结果: 转换后的字符串
	 */
	public static String lowerCase(String str) {
		if (str == null)
			return null;
		byte strbuf[] = str.getBytes();
		for (int i = 0; i < strbuf.length; i++)
			if (strbuf[i] <= 90 && strbuf[i] >= 65)
				strbuf[i] = (byte) (strbuf[i] + 32);

		return new String(strbuf);
	}

	/**
	 * @函数功能: 将字符串转换为大写
	 * @输入参数: 待转换的字符串
	 * @输出结果: 转换后的字符串
	 */
	public static String upperCase(String str) {
		if (str == null)
			return null;
		byte strbuf[] = str.getBytes();
		for (int i = 0; i < strbuf.length; i++)
			if (strbuf[i] <= 122 && strbuf[i] >= 97)
				strbuf[i] = (byte) (strbuf[i] - 32);

		return new String(strbuf);
	}

	/**
	 * @函数功能: 将一个字符串的首字母改为大写或者小写
	 * @输入参数: String srcString 源字符串
	 * @输入参数: boolean flag 大小写标识，ture小写，false大些
	 * @输出结果: 改写后的新字符串
	 */
	public static String toLowerCaseInitial(String srcString, boolean flag) {
		StringBuilder sb = new StringBuilder();
		if (flag) {
			sb.append(Character.toLowerCase(srcString.charAt(0)));
		} else {
			sb.append(Character.toUpperCase(srcString.charAt(0)));
		}
		sb.append(srcString.substring(1));
		return sb.toString();
	}

	/**
	 * @函数功能: 截取byteBuff中从pos1位置到pos2位置的字符串
	 * @输入参数: byte bytes[]待截取的byte[]
	 * @输入参数: int pos1开始位置
	 * @输入参数: int pos2结束位置
	 * @输出结果: 截取后的字符串
	 */
	public static String byteBuffToString(byte bytes[], int pos1, int pos2) {
		if (bytes == null || pos2 < pos1)
			return "";
		else
			return new String(bytes, pos1, pos2 - pos1);
	}

	/**
	 * @函数功能: 用逗号分割String
	 * @输入参数: String str 待分割的字符串
	 * @输出结果: ret 分割后的String[]
	 */
	public static String[] spliteStr(String str) {
		StringTokenizer st = new StringTokenizer(str, ",");
		String ret[] = new String[st.countTokens()];
		for (int i = 0; st.hasMoreTokens(); i++)
			ret[i] = st.nextToken();

		return ret;
	}

	/**
	 * @函数功能: 用分割符separator分割str
	 * @输入参数: String str 待分割的字符串
	 * @输入参数: String separator 分隔符
	 * @输出结果: ret 分割后的String[]
	 */
	public static String[] spliteStr(String str, String separator) {
		StringTokenizer st = new StringTokenizer(str, separator);
		String ret[] = new String[st.countTokens()];
		for (int i = 0; st.hasMoreTokens(); i++)
			ret[i] = st.nextToken();

		return ret;
	}

	/**
	 * @函数功能: 分割date，date初始格式如20120524
	 * @输入参数: String date 待分割的日期字符串
	 * @输出结果: ret 分割后的String[]
	 */
	public static String[] splitDate(String date) {
		String ret[] = new String[3];
		ret[0] = date.substring(0, 4);
		ret[1] = date.substring(4, 6);
		ret[2] = date.substring(6, 8);
		return ret;
	}

	/**
	 * @函数功能: 通过输入的年y月m日d，组成格式为20120524格式的日期
	 * @输入参数: String y 年
	 * @输入参数: String m 月
	 * @输入参数: String d 日
	 * @输出结果: 生成的日期字符串
	 */
	public static String genDateStr(String y, String m, String d) {
		StringBuffer sb = new StringBuffer("00000000");
		sb = sb.replace(4 - y.length(), 4, y);
		sb = sb.replace(6 - m.length(), 6, m);
		sb = sb.replace(8 - d.length(), 8, d);
		return sb.toString();
	}

	/**
	 * @函数功能: 将输入的数字字符串，格式化为1,111,111,111,111.00格式的字符串
	 * @输入参数: String amount待格式化的数字字符串
	 * @输出结果: 格式化后的字符串
	 */
	public static String formateAmount(String amount) {
		try {
			DecimalFormat nf = new DecimalFormat();
			nf.applyPattern("#,###,###,###,###.00");
			amount = nf.format(Double.parseDouble(amount));
			if (amount.substring(0, 1).equals("."))
				amount = (new StringBuilder()).append("0").append(amount).toString();
		} catch (Exception e) {
			return "";
		}
		return amount;
	}

	/**
	 * @函数功能: 将输入的格式为1,111,111,111,111.00的数字字符串解析为11111111111字符串
	 * @输入参数: String amount待解析的数字字符串
	 * @输出结果: 解析后的字符串
	 */
	public static Number parseAmount(String amount) {
		try {
			DecimalFormat nf = new DecimalFormat();
			ParsePosition pp = new ParsePosition(0);
			nf.applyPattern("#,###,###,###,###.00");
			Number amt = nf.parse(amount, pp);
			return amt;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * @函数功能: 替换字符串
	 * @输入参数: String baseString 源字符串
	 * @输入参数: String sourceString 待替换的字符串
	 * @输入参数: String targetString 替换成的字符串
	 * @输出结果: 替换后字符串
	 */
	public static String replaceString(String baseString, String sourceString, String targetString) {
		if (baseString == null || sourceString == null || targetString == null)
			return baseString;
		int ln1 = sourceString.length();
		int ln2 = targetString.length();
		if (ln1 == 0)
			return baseString;
		String returnStr = baseString;
		for (int i = 0; returnStr.indexOf(sourceString, i) >= 0; i += ln2) {
			i = returnStr.indexOf(sourceString, i);
			if (i == 0) {
				returnStr = (new StringBuilder()).append(targetString).append(returnStr.substring(ln1)).toString();
				continue;
			}
			if (i + ln1 == baseString.length())
				returnStr = (new StringBuilder()).append(returnStr.substring(0, i)).append(targetString).toString();
			else
				returnStr = (new StringBuilder()).append(returnStr.substring(0, i)).append(targetString)
						.append(returnStr.substring(i + ln1)).toString();
		}

		return returnStr;
	}

	/**
	 * @函数功能: 从源字符串str截取长度为length的字符串，注意汉字长度为2,截取前过滤空格
	 * @输入参数: String str 源字符串
	 * @输入参数: int length 要截取的长度
	 * @输出结果: 截取后的字符串
	 */
	public static String cutString(String str, int length) {
		byte byteArray[] = new byte[length];
		try {
			byte temp[] = str.getBytes("GBK");
			int k = 0;
			for (int i = 0; i < length; i++) {
				byteArray[i] = temp[i];
				if (temp[i] < 0)
					k++;
			}
			if (k % 2 == 1)
				byteArray[length - 1] = 32;
			str = new String(byteArray, "GBK");
		} catch (UnsupportedEncodingException e) {
		}
		return str;
	}

	/**
	 * @函数功能: 从源字符串str截取长度为length的字符串，注意汉字长度为2,截取前不过滤空格
	 * @输入参数: String str 源字符串
	 * @输入参数: int length 要截取的长度
	 * @输出结果: 截取后的字符串
	 */
	public static String subSpaceString(String str, int length) {
		byte byteArray[] = new byte[length];
		byte temp[];
		try {
			temp = str.getBytes("GBK");
			if (temp.length > length)
				return cutString(str, length);

			for (int i = 0; i < temp.length; i++)
				byteArray[i] = temp[i];

			for (int k = temp.length; k < length; k++)
				byteArray[k] = 32;

			str = new String(byteArray, "GBK");
		} catch (UnsupportedEncodingException e) {
		}
		return str;
	}

	/**
	 * @函数功能: 计算字符串s中出现char c的次数
	 * @输入参数: String s 源字符串
	 * @输入参数: char c 待计算的字符
	 * @输出结果: c出现的次数
	 */
	public static int count(String s, char c) {
		int count = 0;
		byte[] sBytes = s.getBytes();
		for (int i = 0; i < sBytes.length; i++) {
			if (sBytes[i] == c) {
				count++;
			}
		}
		return count;
	}

	/**
	 * 查询字符串baseString中findString出现的次数
	 *
	 * @param baseString
	 * @param findString
	 * @return
	 */
	public static int count(String baseString, String findString) {

		if (baseString == null || findString == null)
			return -1;
		int baseLength = baseString.length();
		int findLength = findString.length();
		if (baseLength < findLength)
			return -1;
		String temp = baseString;

		int count = 0;
		int index = temp.indexOf(findString);
		while (index != -1) {
			temp = temp.substring(index + findLength);
			index = temp.indexOf(findString);
			count++;
		}
		return count;
	}

	/**
	 * @函数功能: 将八进制字符串转化为字节数组
	 * @输入参数: String hexStr 源八进制字符串
	 * @输出结果: 替换后字节数组
	 */
	public static byte[] hexStringToByteArray(String hexStr) {
		String s = hexStr != null ? hexStr : "";
		int len = s.length() >> 1;
		byte b[] = s.getBytes();
		byte d[] = new byte[len];
		for (int i = 0; i < len * 2; i++) {
			int shift = i % 2 != 1 ? 4 : 0;
			d[i >> 1] |= Character.digit((char) b[i], 16) << shift;
		}
		return d;
	}

	/**
	 * @函数功能: 将字节数组转化为八进制字符串
	 * @输入参数: byte b[] 源字节数组
	 * @输出结果: 替换后八进制字符串
	 */
	public static String byteArrayToHexString(byte b[]) {
		if (b == null || b.length < 1)
			return "";
		StringBuffer d = new StringBuffer(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			char hi = Character.forDigit(b[i] >> 4 & 15, 16);
			char lo = Character.forDigit(b[i] & 15, 16);
			d.append(Character.toUpperCase(hi));
			d.append(Character.toUpperCase(lo));
		}
		return d.toString();
	}

	/**
	 * 将字节数组转换成16进制字符串
	 *
	 * @param bytes
	 *            即将转换的数据
	 * @return 16进制字符串
	 */
	public static String bytesToHexString(byte[] bytes) {
		StringBuffer sb = new StringBuffer(bytes.length);
		String temp = null;
		for (int i = 0; i < bytes.length; i++) {
			temp = Integer.toHexString(0xFF & bytes[i]);
			if (temp.length() < 2) {
				sb.append(0);
			}
			sb.append(temp);
		}
		return sb.toString();
	}

	/**
	 * 把16进制字符串转换成字节数组
	 *
	 * @param hexstr
	 * @return
	 */
	public static byte[] HexString2Bytes(String hexstr) {
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) ((parse(c0) << 4) | parse(c1));
		}
		return b;
	}

	private static int parse(char c) {
		if (c >= 'a')
			return (c - 'a' + 10) & 0x0f;
		if (c >= 'A')
			return (c - 'A' + 10) & 0x0f;
		return (c - '0') & 0x0f;
	}

	/**
	 * 将用“|”分隔的字符串转换为字符串集合列表，剔除分隔后各个字符串前后的空格
	 *
	 * @param series
	 *            将用“|”分隔的字符串
	 * @return 字符串集合列表
	 */
	public static List<String> series2List(String series) {
		return series2List(series, "\\|");
	}

	/**
	 * 将用正则表达式regex分隔的字符串转换为字符串集合列表，剔除分隔后各个字符串前后的空格
	 *
	 * @param series
	 *            用正则表达式分隔的字符串
	 * @param regex
	 *            分隔串联串的正则表达式
	 * @return 字符串集合列表
	 */
	private static List<String> series2List(String series, String regex) {
		List<String> result = new ArrayList<String>();
		if (series != null && regex != null) {
			for (String s : series.split(regex)) {
				if (s.trim() != null && !s.trim().equals(""))
					result.add(s.trim());
			}
		}
		return result;
	}

	/**
	 * @param strList
	 *            字符串集合列表
	 * @return 通过“|”串联为一个字符串
	 */
	public static String list2series(List<String> strList) {
		StringBuffer series = new StringBuffer();
		for (String s : strList) {
			series.append(s).append("|");
		}
		return series.toString();
	}

	public static String beforeFilling(String orgiMessage, String filling, int lastLength) {
		if (orgiMessage == null)
			orgiMessage = "";
		if (orgiMessage.length() > lastLength)
			return orgiMessage.substring(orgiMessage.length() - lastLength, orgiMessage.length());
		StringBuffer sb = new StringBuffer();
		for (int i = orgiMessage.length(); i < lastLength; i++)
			sb.append(filling == null ? "" : filling);
		return sb.append(orgiMessage).toString();

	}

	public static byte[] afterFillingWithSpace(byte[] orgi, int lastLength) {
		if (orgi == null)
			return null;
		byte[] data = new byte[lastLength];
		int len = orgi.length > lastLength ? lastLength : orgi.length;
		for (int i = 0; i < len; i++) {
			data[i] = orgi[i];
		}
		for (int i = len; i < lastLength; i++)
			data[i] = '\0';
		return data;
	}

	public static String defaultString(String s) {
		if (s == null)
			return "";
		else
			return s.trim();
	}

	public static String defaultStringNoTrim(String s) {
		if (s == null)
			return "";
		else
			return s;
	}

	/**
	 * source按split分割的各域中是否包含search字符串
	 *
	 * @param source
	 * @param search
	 * @param split
	 * @return
	 */
	public static boolean contains(String source, String search, String split) {
		if (isEmpty(source))
			return false;
		if (isEmpty(search))
			return true;
		String[] sps = source.split(split);
		for (String sp : sps) {
			if (sp.trim().equals(search))
				return true;
		}
		return false;
	}

	public static String convertStreamToString(InputStream is) throws IOException {
		int i = -1;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		String content = baos.toString("GBK");

		return content;
	}

	public static InputStream convertStringToStream(String str) throws UnsupportedEncodingException {
		InputStream is = new ByteArrayInputStream(str.getBytes("GBK"));
		return is;

	}



	public static String byteArray2HexStr(byte[] bs) {
		StringBuilder md5StrBuff = new StringBuilder();
		for (byte b : bs) {
			if (Integer.toHexString(0xFF & b).length() == 1) {
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & b));
			} else {
				md5StrBuff.append(Integer.toHexString(0xFF & b));
			}
		}
		return md5StrBuff.toString();
	}
}
